package com.wokeMy.view.channe.hengfeng;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.woke.MybankblindActivity;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.data.Data_bindcarlist;
import com.woke.data.UnionPayChannel;
import com.woke.httpupload.FileProviderUtils;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.channe.changjie.CjieKjzfActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class HengfengRzActivity extends BaseActivity implements View.OnClickListener,EasyPermissions.PermissionCallbacks{
    ImageView back_hfeng_iv,zidcard_hfeng_iv,fidcard_hfeng_iv,sidcard_hfeng_iv,zyhcard_hfeng_iv,fyhcard_hfeng_iv,mmz_hfeng_iv;
    RelativeLayout khcard_hfeng_rl,zidcard_hfeng_rl,fidcard_hfeng_rl,sidcard_hfeng_rl,zyhcard_hfeng_rl,fyhcard_hfeng_rl,mmz_hfeng_rl;
    Button kait_hfeng_bt;
    TextView khk_hfeng_tv;


    Data_bindcarlist listdata;
    UnionPayChannel unionPayChannel;
    String pay_card_no,bankCode;
    String user_id;
    int way_id;// 通道 另外判断通道  77畅捷山高 78 商旅；
    String controller;
    int payWay;
    String useName,merchantName,merchantBillName,legalPersonID,merchantPersonPhone;
    private float money;
    Dialog dialog;

    private String photoTemp;
    private String photoName;
    Uri imageUri;
    private File tempFile;//裁剪后的图片

    private final int PHOTO_CAPTURE = 0x11;//拍照
    private final int PHOTO_PIC = 0x12;//相册
    private final int PHOTO_CROP = 0x13;//裁剪

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_hengfeng_rz);
    }

    @Override
    public void initActivity() {
        back_hfeng_iv.setOnClickListener(this);
        khcard_hfeng_rl.setOnClickListener(this);
        kait_hfeng_bt.setOnClickListener(this);
        zidcard_hfeng_rl.setOnClickListener(this);
    }

    @Override
    public void initView() {
        back_hfeng_iv = myFindViewById(R.id.back_hfeng_iv);
        khcard_hfeng_rl = myFindViewById(R.id.khcard_hfeng_rl);
        khk_hfeng_tv = myFindViewById(R.id.khk_hfeng_tv);
        //身份证
        zidcard_hfeng_rl = myFindViewById(R.id.zidcard_hfeng_rl);
        zidcard_hfeng_iv = myFindViewById(R.id.zidcard_hfeng_iv);
        fidcard_hfeng_rl = myFindViewById(R.id.fidcard_hfeng_rl);
        fidcard_hfeng_iv = myFindViewById(R.id.fidcard_hfeng_iv);
        sidcard_hfeng_rl = myFindViewById(R.id.sidcard_hfeng_rl);
        sidcard_hfeng_iv = myFindViewById(R.id.sidcard_hfeng_iv);
        //银行卡
        zyhcard_hfeng_rl = myFindViewById(R.id.zyhcard_hfeng_rl);
        zyhcard_hfeng_iv = myFindViewById(R.id.zyhcard_hfeng_iv);
        fyhcard_hfeng_rl = myFindViewById(R.id.fyhcard_hfeng_rl);
        fyhcard_hfeng_iv = myFindViewById(R.id.fyhcard_hfeng_iv);
        //门头证
        mmz_hfeng_rl = myFindViewById(R.id.mmz_hfeng_rl);
        mmz_hfeng_iv = myFindViewById(R.id.mmz_hfeng_iv);


        kait_hfeng_bt = myFindViewById(R.id.kait_hfeng_bt);



    }

    @Override
    public void initData() {
        MyApp myApp=(MyApp)getApplication();
        Intent intent=getIntent();
        Datas_load datas_load=myApp.getDatas_load();
        Log.e("legalPersonName",datas_load.toString());
        user_id=datas_load.getId();
        unionPayChannel = (UnionPayChannel)(intent.getSerializableExtra("UnionPayChannel"));
        money=intent.getFloatExtra ("money", 0.01f);
        Log.e("unionPayChannel",unionPayChannel.toString());
        way_id=unionPayChannel.getWay();
        controller =unionPayChannel.getController();
        payWay=unionPayChannel.getKind();
        String name="名字为空";
        if (!datas_load.getUser_nicename().equals("")){
            name=datas_load.getUser_nicename();
        }else {
            name=datas_load.getCom_name();
        }
        useName=name;
        merchantName=name+"的商户";
        merchantBillName=name+"的商户";
        legalPersonID=datas_load.getUser_no();
        merchantPersonPhone=datas_load.getUser_login();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_hfeng_iv:
                finish();
                break;
            case R.id.khcard_hfeng_rl:
                Intent intent = new Intent (HengfengRzActivity.this, MybankblindActivity.class);
                intent.putExtra ("czhiortxian", "rhlz");
                startActivityForResult (intent, Constant.REQUEST_RHLZ);
                break;
            case R.id.zidcard_hfeng_rl:
                new PopupWindows(HengfengRzActivity.this, 1);
                break;
            case R.id.kait_hfeng_bt:


                //                bankCode=lhk_cjie_et.getText().toString().trim();
                bankCode="111111";
                if (pay_card_no==null||pay_card_no.equals("")){
                    Toast.makeText(this,"请选择结算卡",Toast.LENGTH_SHORT).show();
                }else if(bankCode==null||bankCode.equals("")) {
                    Toast.makeText(this,"请填写联行号",Toast.LENGTH_SHORT).show();
                }else{
                    if (!fastClick()) {
                        dialog = Util.createLoadingDialog(HengfengRzActivity.this);
                        rhlzSelft();
                    }
                }

                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==Constant.RESPONSE_RHLZ){
            listdata=(Data_bindcarlist)data.getSerializableExtra("listdata");
            pay_card_no=listdata.cardno;
            khk_hfeng_tv.setText(pay_card_no);
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_PIC:
                    if (data != null && data.getData() != null) {
                        detailOnActivityResult(PHOTO_PIC, data.getData());
                    }
                    break;
                case PHOTO_CAPTURE:
                    detailOnActivityResult(PHOTO_CAPTURE, Uri.fromFile(new File(photoTemp)));
                    break;
                case PHOTO_CROP:
                    if (data != null && data.getData() != null) {
                        Log.e("Camera", "PHOTO_CROP  1");
                        detailOnActivityResult(PHOTO_CROP, data.getData());
                    } else {
                        Log.e("Camera", "PHOTO_CROP  2");
                        detailOnActivityResult(PHOTO_CROP, Uri.fromFile(tempFile));
                    }
                    break;
            }
        }
    }
    //    畅捷入驻（本通道）
    public void rhlzSelft(){
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",user_id);
        params.put("way",way_id);   //通道
        params.put("bankAccountNo",pay_card_no);
        params.put("bankChannelNo",bankCode);
        params.put("merName",merchantName);
        params.put("merAbbr",merchantBillName);
        // params.put("creditCardNo","6225757545273378");
        Log.e(" 畅捷入驻（本通道）params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.CJRZ_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("畅捷入驻（本通道）/////////", result);
                    try {

                        JSONObject  jsonObject =new JSONObject(result);
                        if (jsonObject.getString("flag").equals("unknown")){
                            Toast.makeText(HengfengRzActivity.this,jsonObject.getString("info"),Toast.LENGTH_SHORT).show();
                            Util.closeDialog(dialog);
                        }else {
                            JSONObject jsonObject1=jsonObject.getJSONObject("data").getJSONObject("data");
                            String respcode=jsonObject1.getString("code");
                            if (respcode.equals("00")){
                                cjFeilv();
                            }else if(respcode.equals("2015")){
                                Toast.makeText(HengfengRzActivity.this,"商户已经入驻过",Toast.LENGTH_SHORT).show();
                            }else {
                                Toast.makeText(HengfengRzActivity.this,jsonObject1.getString("respmsg"),Toast.LENGTH_SHORT).show();
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }
    //    畅捷新增另外一个费率
    public void cjFeilv(){
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("user_id",user_id);
        params.put("bankAccountNo",pay_card_no); //结算卡
        params.put("changeType","3");//1 交易费率变更 2 银行卡信息变更 3 交易费率新增 4 提现费率变更
        // params.put("creditCardNo","6225757545273378");
        Log.e(" 畅捷新增另外一个费率params",params.toString());
        //url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
        ahc.post(Constant.CJXZFR_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Util.closeDialog(dialog);
                String result = null;
                try {
                    result = new String(bytes, "utf-8");
                    //                        Toast.makeText(SeletCardActivity.this, result, Toast.LENGTH_SHORT).show();
                    Log.e("畅捷新增另外一个费率/////////", result);
                    try {
                        JSONObject  jsonObject =new JSONObject(result);
                        JSONObject jsonObject1=jsonObject.getJSONObject("data").getJSONObject("data");
                        String respcode=jsonObject1.getString("code");
                        if (respcode.equals("00")){
                            Toast.makeText(HengfengRzActivity.this,"开通成功",Toast.LENGTH_LONG).show();
                            finish();
                            Intent intent2 = new Intent();
                            intent2.setClass (HengfengRzActivity.this,
                                    CjieKjzfActivity.class);
                            intent2.putExtra("UnionPayChannel",unionPayChannel);
                            intent2.putExtra ("money",money);
                            startActivity (intent2);
                        }else if(respcode.equals("2015")){
                            Toast.makeText(HengfengRzActivity.this,"商户已经入驻过",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(HengfengRzActivity.this,jsonObject1.getString("respmsg"),Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Util.closeDialog(dialog);
            }
        });
    }


    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, final int parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LinearLayout.LayoutParams.FILL_PARENT);
            setHeight(LinearLayout.LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(view, Gravity.BOTTOM, 0, 0);
            update();

            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        methodRequiresTwoPermission();
                    } else {
                        photo();
                    }
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent i = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(i, PHOTO_PIC);
                    dismiss();
                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }
    private static final int CAMERA = 88;

    @AfterPermissionGranted(CAMERA)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            photo();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "需要读取本地文件/相机权限",
                    CAMERA, perms);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA) {
            photo();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == CAMERA) {
            new AlertDialog.Builder(this).setMessage("请在<权限管理>里打开相机权限")
                    .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.fromParts("package", getPackageName(), null));
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .create()
                    .show();
        }
    }
    private void photo() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            // Ensure that there's a camera activity to handle the intent
            File photo = FileProviderUtils.createImageFile(this);

            if (photo != null) {
                photoTemp = photo.getAbsolutePath();
                imageUri = Uri.fromFile(photo);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent, PHOTO_CAPTURE);
            }
        }
    }
    private void detailOnActivityResult(int requestCode, Uri uri) {
        switch (requestCode) {
            case PHOTO_CAPTURE:
                //拍照
                sendBroadcast(
                        new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            case PHOTO_PIC:
                //选择图片
                //然后裁剪

                tempFile = FileProviderUtils.createImageFile(this);
                Log.e("cache", tempFile.getAbsolutePath());
                //					Uri imageUriTemp = FileProvider.getUriForFile (this, "com.zhongcai.online.fileProvider", photo);
                Uri imageUriTemp = Uri.fromFile(tempFile);
                Log.e("cache uri", imageUriTemp.toString());

                GlideApp.with(this)
                        .load(uri).placeholder(R.mipmap.icn__launch_oem)
                        .error(R.mipmap.icn__launch_oem)

                        .into(zidcard_hfeng_iv);
                break;

            case PHOTO_CROP:
                //裁剪后,则上传图片
                photoName = tempFile.toString();
//                uploadcheckmap(photoName);
                break;
        }
    }
}
